<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" :title="title" @ok="handleSubmit" 
    :width="750" 
    :minHeight="500"
    destroyOnClose
  >
    <Tabs 
      v-model:activeKey="state.channelType" 
      :tabBarGutter="10" :class="`${prefixCls}-tab`"
      @change="handleTabChange" v-if="!state.isClickChannel"
    >
      <template v-for="item in state.channelList" :key="item.code">
        <TabPane :tab="item.name" forceRender>
         
        </TabPane>
      </template>
    </Tabs>
  
    <BasicForm @register="registerForm" >
      <template #contentEdit="{ model, field }">
        <MyCodeEditor v-model:value="model[field]" mode="html" height="130px" :fullScreen="true" :zIndex="20000" />
        <!-- <RenderHtml v-else :renderHtml="false" :text="model[field]" height="130px" :fullScreen="true" :zIndex="20000" /> -->
        <!-- <InputTextArea v-else v-model:value="model[field]" readOnly :autoSize=" { minRows: 2, maxRows: 8 }"/> -->
      </template>
    </BasicForm>

    <Divider v-if="!state.loading">模板字段配置</Divider>
    <Alert banner
      closable style="margin-bottom: 10px;"
      type="info" 
    > 
      <template #description>
        <span v-for="(item, index) in state.fieldSettingTips" :key="index"> {{ index + 1 }}. {{ item }} <br/></span>
      </template>
    </Alert>
    <JVxeTable
      v-if="!state.loading"
      ref="tableRef"
      stripe
      keepSource
      rowSelection
      sortKey="sortNo"
      rowKey="msgField"
      :auto-resize="true" 
      :sync-resize="state.activeKey"
      :maxHeight="600"
      :disabledRows="{ isPk: [true] }"
      :loading="state.loading"
      :disabled="state.disabled"
      :columns="state.columns"
      :dataSource="state.dataSource"
      v-bind="vuxTableProps"
      @selectRowChange="handleSelectdRow"
    >
      <template #toolbarAfter>

      </template>
    </JVxeTable>

    <!-- 底部展示仅保存、保存并关闭 -->
    <template #footer>
      <a-button @click="handleSubmit(false)" type="primary" :loading="state.saveLoading" ghost>仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="state.saveLoading">保存并关闭</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, nextTick, reactive, onMounted } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { channelConfigSchema } from '../data';
import { saveOrUpdateNoticeChannel, settingNoticeChannel, getNoticeChannel } from '../api';
import { useMessage } from '/@/hooks/web/useMessage';
import { Tabs, Alert, Input } from 'ant-design-vue';
import { MyCodeEditor } from '/@/components/My/Editor/index'
import { JVxeTypes, JVxeColumn } from '/@/components/jeecg/JVxeTable/types'
import { Divider } from 'ant-design-vue';
import { VxeGridProps } from 'vxe-table'
import { useDesign } from '/@/hooks/web/useDesign';
import { isHtml } from '/@/utils/common/htmlUtil';
import { useUserStore } from '/@/store/modules/user'
import { isNullOrUnDef } from '/@/utils/is';
import { ChannelTypeEnum } from '../model';
import { isManageOrPlatform }from '/@/utils/tenant'
const userStore = useUserStore()

import RenderHtml from '/@/components/My/RenderHtml.vue';
const InputTextArea = Input.TextArea
const { prefixCls } = useDesign('config-channel');

const TabPane = Tabs.TabPane

const { createMessage } = useMessage()

const emit = defineEmits(['register', 'success']);

const vuxTableProps = ref<VxeGridProps<any>>({
  editConfig: {
    trigger: 'click',
    beforeEditMethod: ({ row, rowIndex, column, columnIndex }) => {
      // 如果消息字段中设置了不可编辑字段的模板消息内容, 则禁用
      if (column.params.key === 'value' && !row.editTpl) {
        createMessage.warn('所选字段的模板内容不可编辑')
        return false
      }

      return true
    }
  },
  checkboxConfig: {
    range: true,
    checkAll: false,
    // 默认勾选指定行（只会在初始化时被触发一次，需要有 row-config.keyField）
    // 这里为了使在设置初始化选中的行, 需要先不让视图渲染, 所以要设置 成v-if = false, 因为vux-table只会执行一次
    // 当初始化选中中行后再设置成true
    checkRowKeys: [],
    // 用于禁止某一行
    checkMethod: ({ row }) => {
      return true
    }
  }
})

const tableRef = ref()
const msgFieldType = JVxeTypes.input
const vxeColumns = ref<JVxeColumn[] >([])


const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
  labelWidth: 90,
  schemas: channelConfigSchema,
  showActionButtonGroup: false,
  wrapperCol: {
    xs: { span: 23 },
    sm: { span: 22 },
  },
});

const state = reactive<any>({
  loading: true,
  saveLoading: false,
  width: 750,
  channelType: '',
  channelInfo: undefined,
  // 是否点击渠道
  isClickChannel: false,
  record: {},
  // 是否可以编辑模板内容
  showEdit: false,
  labelCol: {},
  channelList: [],
  fieldSettingTips: [
    '推送的第三方模板(微信小程序/微信公众号)里有的字段才勾选，如果没有请勿勾选。',
    '这里的模板字段对应到第三方渠道消息中的模板字段',
    '只有勾选某一行, 修改模板字段名才会生效',
    // '以 sl_ 开头的模板字段名, 会将值转成短链(short link)',
  ],

  // 模板字段配置
  columns: vxeColumns,
  // 模板字段数据
  dataSource: [],
  isUpdate: false,
  disabled: false
})


const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  try {
    await resetFields();
    state.loading = true
    setModalProps({ confirmLoading: false, loading: true });  
    state.record = data.record
    state.isClickChannel = !!data.selectedChannel
    state.channelList = data.record.channelList
    state.channelType = data.selectedChannel?.code || state.channelList[0].code
    state.channelInfo = data.selectedChannel || state.channelList[0]
    state.isUpdate = !!state.channelInfo.id
    // state.showEdit = data.showEdit
    // state.disabled = !isManageOrPlatform(userStore)

    // setVxeColumns(state.disabled ? JVxeTypes.normal : JVxeTypes.input)
    setVxeColumns(JVxeTypes.input)

    state.dataSource = (data.record.msgFields || []).map((e) => ({
      msgField: e.key, 
      desc: e.desc, // 描述
      key: e.key, // 模板的字段(默认和消息字段一样, 不过可以单独指定)
      editTpl: e.editTpl,

    }))
    console.log('record', state.record);
    if (state.channelType == ChannelTypeEnum.WX_MP) {
      setProps({ labelWidth: 100 })
    }

    if (state.isUpdate) {
      await initChannelSetting(state.channelInfo?.id)
    } else {
      state.loading = false
      setModalProps({ loading: false })
      // @ts-ignore
      const checkRowKeys = vuxTableProps.value?.checkboxConfig?.checkRowKeys
      checkRowKeys?.splice(0, checkRowKeys.length)
      await setFieldsValue({
        channelType: state.channelType
      })
    }
  } catch(e) {
    createMessage.error(`未知异常 [${e}]`)
  } finally {
    setModalProps({ loading: false });  
    state.loading = false
  }
});

const title = computed(() => {
  return state.isClickChannel ? `配置 ${state.record.name}-${state.channelInfo.name} 渠道` : `编辑 ${state.record.name} 渠道`
});

const setVxeColumns = (msgFieldType = JVxeTypes.input) => {
  vxeColumns.value = [
    { 
      title: '字段名称', key: 'desc', width: 150,
      validateRules: [{ required: true, message: '${title}不能为空' }],
    },
    { 
      title: '消息字段', key: 'msgField',  type: JVxeTypes.normal, width: 150, 
      titleHelp: { message: '推送消息时传递的字段名' },
    }, 
    { 
      title: '模板字段', key: 'key', type: msgFieldType, width: 150,
      titleHelp: { message: '第三方模板中的字段名' },
      validateRules: [{ required: true, message: '${title}不能为空' }],
    },
    { 
      title: '模板内容', key: 'value', type: JVxeTypes.input, defaultValue: '', align: 'center'
    },
  ]
}

const handleSelectdRow = (rows) => {
  // tableRef.value.gridRef.setCheckboxRow(state.dataSource[0], true)
  console.log('rowsKey: ', rows.selectedRows);
}
const handleTabChange = async (code) => {
  await resetFields()
  tableRef.value?.gridRef?.clearCheckboxRow()
  console.log('channelTypeCode', code)
  state.channelType = code
  state.channelInfo = state.channelList.filter(e => e.code === code)[0]
  state.isUpdate = !!state.channelInfo?.id
  if (state.isUpdate) {
    await initChannelSetting(state.channelInfo.id)
  }
  setFieldsValue({ channelType: code })
}

const initChannelSetting = async (channelId) => {
  state.loading = true
  setModalProps({ loading: true })
  try {
    const channelData = await getNoticeChannel({ id: channelId})
    if(channelData) {
      const selectedRowKeys : any = Object.keys(channelData.settings?.tplField)
      console.log('selectedRowKeys', selectedRowKeys)

      state.dataSource = state.dataSource.map(e => {
        const tplField = channelData.settings?.tplField[e.msgField]
        return {
          ...e, value: tplField?.value, key: tplField?.key || e.key
        }
      })
      // @ts-ignore
      const checkRowKeys = vuxTableProps.value?.checkboxConfig?.checkRowKeys
      checkRowKeys?.splice(0, checkRowKeys.length)
      checkRowKeys?.push(...selectedRowKeys)
      const settings = channelData.settings
      for(const key in settings) {
        if (isNullOrUnDef(settings[key])) {
          delete settings[key]
        }
      }
      await setFieldsValue({
        ...settings, 
        status: channelData.status,
        channelType: state.channelType
      });
    }
  } catch(e) {
    console.error(e)
  } finally {
    let time = setTimeout(() => {
      setModalProps({ loading: false })
      clearTimeout(time)
    }, 200)
    state.loading = false
  }
  
}

async function handleSubmit(isClose) {
  state.saveLoading = true
  try {
    let values = await validate();
    const tplField = {}
    tableRef.value!.getSelectedData().forEach(e => {
      tplField[e.msgField] = {
        key: e.key,
        desc: e.desc,
        value: e.value
      }
    })
    const reqParams = {
      settings: {
        tplField, 
        ...values
      },
      id: state.channelInfo?.id,
      noticeId: state.record.id,
      channelType: state.channelType,
      status: values.status
    }

    console.log('reqParams', reqParams)
    setModalProps({ confirmLoading: true });
    await saveOrUpdateNoticeChannel(reqParams, state.isUpdate);
    if (isClose) {
      closeModal();
      emit('success');
    }
    createMessage.success(`配置【${state.channelInfo.name}】成功`)
  } finally {
    state.saveLoading = false
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less">
@prefix-cls: ~'@{namespace}-config-channel';

.@{prefix-cls} {
  &-tab {
    margin-bottom: -15px !important;
  }
}


</style>
